import Vue from 'vue'
import Vuex from 'vuex'
import $H from '../common/request.js'
import $C from '../common/config.js'
import io from "../common/uni-socket.io.js"

Vue.use(Vuex)

export default new Vuex.Store({
	state: {
		lgStatus: false,
		bgColor: uni.getStorageSync('bgs') || 'while',
		token: "",
		socket: null,
		users: null,
		currency: {},
		orderNum: 0,
		tabbarIndex: 0,
		lang: uni.getStorageSync('lang') || 'en'
	},
	mutations: {
		setLang(state, lang) {
			state.lang = lang
		},
		setBg(state, bg) {
			state.bgColor = bg
			if ('black' == bg) {
				uni.setStorageSync('bgColor', true)
				uni.setStorageSync('bgs', 'black')
			} else {
				uni.setStorageSync('bgColor', false)
				uni.setStorageSync('bgs', 'while')
			}

		},
		changeTabbarIndex(state, index) {
			state.tabbarIndex = index;
			console.log('uvexIndex', state.tabbarIndex);
		},
		setOrNum(state, order) {
			state.orderNum = order
		},
		changelgStatus() {
			state.lgStatus = true

		},
		login(state, token) {

			state.lgStatus = true
			state.token = token
			uni.setStorageSync('token', token)
		},
		logout(state) {
			state.users = {}
			state.token = ""
			uni.removeStorageSync('user')
			uni.removeStorageSync('token')
			state.lgStatus = false
		},
		setUser(state, user) {
			state.users = user
			uni.setStorageSync('user', JSON.stringify(user))
		},
		setCurrency(state, curs) {
			state.currency = curs

		},
		initUser(state) {
			let user = uni.getStorageSync('user')
			console.log('触发我了邀请？？？')
			if (user) {
				state.users = JSON.parse(user)
				state.lgStatus = true
			}
		}


	},
	actions: {
		connectSocket({
			state,
			dispatch
		}) {

			const sockets = io($C.socketUrl, {
				query: {},
				transports: ['websocket', 'polling'],
				reconnection: true,
				timeout: 5000

			})




			sockets.on('connect', () => {
				console.log('已链接')
				state.socket = sockets
				const {
					id
				} = sockets


			})

			sockets.on('error', () => {
				state.socket = null
				console.log('连接失败')
			})
			sockets.on('disconnect', () => {
				state.socket = null
				console.log('已断开')
			})
		}
	}
})